package com.cmwa.scbp.sys.schedule.quartz;

import java.lang.reflect.Method;
import java.util.Date;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.cmwa.scbp.sys.schedule.entity.ScheduleVo;
import com.cmwa.scbp.sys.schedule.service.impl.ScheduleServiceImpl;
import com.cmwa.scbp.utils.spring.SpringContextUtil;

@DisallowConcurrentExecution
public class QuartzJobBasic implements Job {

	private static Logger logger = LoggerFactory.getLogger(QuartzJobBasic.class);

	private static final String SUCCESS = "执行成功!";
	private static final String ERROR = "执行失败!";

	@Override
	public void execute(JobExecutionContext context) {
		try {
			long startMillis = System.currentTimeMillis();
			
			ScheduleVo scheduleJob = (ScheduleVo) context.getMergedJobDataMap().get(LoadRepositoryJob.JOB_DATA_MAP_KEY_DEFAULT);
			logger.info("定时任务执行开始，jobName：" + scheduleJob.getJobName() + "， jobGroup：" + scheduleJob.getJobGroup());
			
			executeJob(scheduleJob);

			long endMillis = System.currentTimeMillis();
			logger.info("定时任务执行结束，jobName：" + scheduleJob.getJobName() + "， jobGroup：" + scheduleJob.getJobGroup() + "，耗时：%s" + (endMillis - startMillis));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void executeJob(ScheduleVo scheduleJob) {
		String result = SUCCESS;
		String jobId = null;
		Date nextFireTime = null;
		try {
			jobId = scheduleJob.getTaskId();
			String jobName = scheduleJob.getJobName();
			String classPath = scheduleJob.getClassPath();
			
			// 获取触发器下次执行时间
			SchedulerFactoryBean schedulerFactoryBean = SpringContextUtil.getBean(SchedulerFactoryBean.class);
			if (schedulerFactoryBean != null) {
				Scheduler scheduler = schedulerFactoryBean.getScheduler();
				Trigger trigger = scheduler.getTrigger(new TriggerKey(scheduleJob.getTriggerName(), scheduleJob.getTriggerGroup()));
				if (trigger != null) {
					nextFireTime = trigger.getNextFireTime();
				}
			}
			
			
			Class<?> clazz = Class.forName(classPath);
			Object obj = SpringContextUtil.getBean(clazz);
			Method m = clazz.getMethod(jobName);
			m.invoke(obj);
		} catch (Exception e) {
			result = ERROR;
			String errmsg = e.getCause().getMessage();
			if (errmsg != null && errmsg.length() > 50) {
				result += errmsg.substring(0, 50);
			} else if (errmsg != null) {
				result += errmsg;
			}
			e.printStackTrace();
			logger.error("定时任务执行异常，jobName：" + scheduleJob.getJobName() + "， jobGroup：" + scheduleJob.getJobGroup());
		} finally {
			try {
				SpringContextUtil.getBean(ScheduleServiceImpl.class).writeLastRunnig(jobId, result, nextFireTime);
			} catch (Exception e) {
				logger.error("QuartzJobBase error:", e);
				e.printStackTrace();
			}

		}
	}

}
